<template>
  <div class="defect-dialog">
    <q-dialog v-model="show" persistent transition-show="scale" transition-hide="scale">
      <q-card class="dialog-content" v-drag style="min-width: 1000px; max-height: 600px">
        <q-card-section class="dialog-title bg-primary">
          <div class="text-center text-white dialog-title">
            <span class="font-size-16">不良原因明细</span>
            <q-btn
              style="font-size: 18px;color: white"
              flat
              round
              dense
              class="iconfont icontubiao-67 white close-btn dialog"
              @click="$emit('close')"
            />
          </div>
        </q-card-section>
        <!-- 显示信息  -->
        <div>
          <div class="q-pa-md padding-l-20 padding-r-20">
            <div class="row">
              <div class="col">车间：{{location.workshop}}</div>
              <div class="col">原因：{{location.reason}}</div>
              <div class="col row">
                <div class="col" style="margin-left:-35px">产品名称：{{location.productName}}</div>
                <div>
                  <q-btn
                    class="btn col"
                    outline
                    @click="exportList"
                    color="primary"
                    label="导出Excel"
                  />
                </div>
              </div>
            </div>
          </div>
          <!-- 图表-->
          <q-table
            :data="tableData"
            :columns="tableColumns"
            row-key="id"
            id="defectTable"
            class="myTable scroll"
            style="margin: 0 0 10px; max-height: 350px"
            hide-bottom
            :pagination.sync="pagination"
            separator="cell"
            no-data-label="暂无数据"
            :loading="isTableLoading"
            color="primary"
          />
        </div>
        <!--  分页-->
        <!-- <pagination :page-cur="pagination.page"
                    :page-size="pagination.rowsPerPage"
                    :total="pagination.rowsNumber"
                    @changePageSize="onPageSizeChange"
                    @changePage="onPageChange"
        style="margin-bottom: 20px" />-->
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
// import Pagination from '../../../components/pagination/index'
import { getBadReportDetail } from '../../../boot/statistics/stop-reason'
// import XLSX from 'xlsx'
import exportJs from './export'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'defect-dialog',
  components: {
    // Pagination
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    defectRowData: Object
  },
  data () {
    return {
      isTableLoading: false,
      location: {
        workshop: '',
        reason: '',
        productName: ''
      },
      // 表格分页配置
      pagination: {
        // 当前页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      // 表格头部数据
      tableColumns: [
        { name: 'indexId', field: 'indexId', label: '序号', align: 'left' },
        {
          name: 'deviceName',
          field: 'deviceName',
          label: '设备名称',
          align: 'center'

        },
        {
          name: 'operatorName',
          field: 'operatorName',
          label: '作业人',
          align: 'center'
        },
        // {
        //   name: 'totalFinishSeconds',
        //   field: 'totalFinishSeconds',
        //   label: '生产产量',
        //   align: 'left'
        // },
        {
          name: 'badSeconds',
          field: 'badSeconds',
          label: '不良数量',
          align: 'center'
        }
        // {
        //   name: 'rate',
        //   field: 'rate',
        //   label: '不良率',
        //   align: 'left'
        // }
      ],
      // 表格内容
      tableData: [],
      queryData: {}
    }
  },
  watch: {
    defectRowData: {
      handler (newPro) {
        this.queryData = newPro
      },
      deep: true,
      immediate: true
    },
    // 监听是否打开
    show (newPro) {
      if (newPro) {
        this.getBadReportDetail()
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  methods: {
    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */

    onPageSizeChange (val) {
      this.pagination.rowsPerPage = val
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange (val) {
      this.pagination.page = val
    },
    // onExcel () {
    //   let workbook = document.querySelector('#defectTable')
    //   let sheet = XLSX.utils.table_to_sheet(workbook, { raw: true })
    //   try {
    //     exportJs.openDownloadDialog(exportJs.sheet2blob(sheet), '不良原因合格率详细报表.xlsx')
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
    // 导出xls 样式
    exportList () {
      // const member = {
      //   month: 'yearMonth',
      //   date: 'date',
      //   week: 'week'
      // }
      // let isDate = member[this.queryData.dateType]
      const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语桢物联'
      const stopReason = `不良原因分析设备明细 (${this.getDate(this.defectRowData.dateRange[0])}-${this.getDate(this.defectRowData.dateRange[1])})`
      const undesirableReason = `不良原因：${this.location.reason}`
      const countTime = `产品名称：${this.location.productName}`
      const position = `车 间：${this.location.workshop}`
      const tableHead = ['序号', '设备名称', '作业人', '不良数量']
      const tableData = []
      const excelName = `${this.getDate(this.defectRowData.dateRange[0])}-${this.getDate(this.defectRowData.dateRange[1])}-${this.location.productName}-不良原因分析设备明细报表`
      const sheetName = `${this.getDate(this.defectRowData.dateRange[0])}-${this.getDate(this.defectRowData.dateRange[1])}不良原因分析设备明细报表`
      this.tableData.forEach(v1 => {
        const item = []
        tableHead.forEach((v2, index) => {
          if (v2 === '序号') {
            item.push(v1.indexId)
          } else if (v2 === '设备名称') {
            item.push(v1.deviceName)
          } else if (v2 === '作业人') {
            item.push(v1.operatorName)
          } else if (v2 === '不良数量') {
            item.push(v1.badSeconds)
          }
        })
        tableData.push(item)
      })
      // console.log('tableData', tableData)
      exportJs.exportCustomerExcel(companyName, stopReason, position, tableHead, tableData, excelName, undesirableReason, countTime, sheetName)
    },
    getDate (date) {
      return moment(date).format('YYYYMMDD')
    },
    isShow (arr, item) {
      let flag = ''
      arr.forEach(i => {
        if (item.indexOf(String(i)) > -1) {
          flag = i
        }
      })
      return flag
    },
    setOprofNum (val) {
      this.oprof_start.num = this.queryParams.devices[0] === 'all' ? val : this.queryParams.devices.length
    },
    // 初始化接口
    getBadReportDetail () {
      this.location.workshop = this.queryData.workshop
      this.location.reason = this.queryData.reason
      this.location.productName = this.queryData.productName
      const member = {
        month: 'yearMonth',
        date: 'date',
        week: 'week'
      }
      let isDate = member[this.queryData.dateType]
      const params = {
        pageNum: this.pagination.page,
        pageSize: this.pagination.rowsPerPage,
        schemeLevel: this.queryData.location.level,
        deviceIds: this.queryData.devices[0] === 'all' ? [] : this.queryData.devices,
        schemeLevelId: this.queryData.location.id,
        startDate: this.queryData[isDate],
        endDate: this.queryData[isDate],
        causeId: this.queryData.causeStopType === '2' ? this.queryData.causeId : '',
        causeGroupId:
          this.queryData.causeStopType === '1' ? this.queryData.causeGroupId : '',
        dateType: this.queryData.dateType,
        productIds: this.queryData.productId,
        type: this.queryData.causeStopType
      }
      this.isTableLoading = true
      getBadReportDetail(params).then(res => {
        this.isTableLoading = false
        const ret = res.data
        // 总条数
        // 日周月 格式
        // this.causeStopType
        ret.map((v, i) => {
          const item = v
          item.indexId = i + 1
          item.deviceName = v.deviceName || '--'
          item.operatorName = v.operatorName || '--'
        })
        //
        this.tableData = ret
      })
    }
  }
}
</script>
<style scoped>
.btn {
  margin-top: -5px;
}
</style>
